import {Post} from '@/api/request'
import router ,{asyncRoutes} from '@/router'
import { getMenu } from "@/api/api";

const user = {
    namespaced: true,
    state:{
        token:localStorage.getItem('token'),
        avatar:'',
        username:'',
        roles:[],
        menus:[]
    },

    mutations:{
        SET_TOKEN:(state,token) =>{
            state.token = token
        },
        SET_AVATAR:(state,avatar) =>{
            state.avatar = avatar
        },
        SET_USERNAME:(state,username) =>{
            state.username = username
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_MENUS: (state, menus) => {
            state.menus = menus
        }
    },

    actions:{
        /* login */
        LoginResult({commit}, userInfo) {
            return new Promise((resolve,reject) =>{
                localStorage.removeItem('token');
                Post("oauth/login?username="+userInfo.loginName+"&password="+userInfo.password,{}).then(response =>{
                    let tokenUser=response;
                    debugger
                    localStorage.setItem('token',tokenUser.access_token)
                    getMenu({}).then(x=>{
                        commit('SET_MENUS',x.data);
                        localStorage.setItem('menus',x.data)
                    }).catch(error =>{
                    })
                    commit('SET_USERNAME',tokenUser.user_name)
                    commit('SET_TOKEN',tokenUser.access_token)
                    resolve(response)
                }).catch(error =>{
                    reject(error)
                })
            })
        },

        /* 用户登出 */
        LogoutResult({commit}) {
            commit('SET_TOKEN','')
            commit('SET_AVATAR','')
            commit('SET_USERNAME','')
            commit('SET_ROLES','')
            commit('SET_MENUS','')
            const Routes = router.getRoutes()
            
            /* 清楚动态路由 */
            asyncRoutes.forEach((item) => {
                router.removeRoute(item.name)
            })
            
            console.log(Routes)
            localStorage.removeItem('token')
        
        }
      
    },

 
}

export default user